// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use encoding::all::GBK;
use encoding::{DecoderTrap, Encoding};
use std::process::Command;
use tauri::Manager;
mod error;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn run_code(code: &str) -> Result<String, String> {
  let res = Command::new("python.exe")
    .current_dir("./python")
    .arg(code)
    .output();
  if res.is_ok() {
    let res = res.unwrap();
    if res.status.success() {
      if let Ok(msg) = GBK.decode(&res.stdout, DecoderTrap::Strict) {
        return Ok(msg);
      }
      let _res = String::from_utf8_lossy(&res.stdout);
      return Ok(_res.into_owned());
    } else {
      if let Ok(msg) = GBK.decode(&res.stderr, DecoderTrap::Strict) {
        return Err(msg);
      }
      let _res = String::from_utf8_lossy(&res.stderr);
      return Err(_res.into_owned());
    }
  } else {
    let err = res.err().unwrap();
    println!("{:?}", err);
    return Err(err.to_string());
  }
}
#[tauri::command]
fn load_node() -> String {
  String::from("value")
}

fn main() {
  tauri::Builder::default()
    .plugin(tauri_plugin_dialog::init())
    .plugin(tauri_plugin_fs::init())
    .setup(|app| {
      let win = app.get_webview_window("main").unwrap();
      #[cfg(debug_assertions)]
      {
        win.open_devtools();
      }
      Ok(())
    })
    .plugin(tauri_plugin_shell::init())
    .invoke_handler(tauri::generate_handler![run_code])
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}
